import pandas as pd
from pprint import pprint
import pymysql


class DataOperation:
    # 初始化属性
    def __init__(self, data, path='', sql='', host='localhost', user='root', password='h518518',
                 database='zhangsan', charset='utf8'):
        try:
            conn = pymysql.connect(host=host, user=user, password=password, database=database, charset=charset)
            if data == 'csv':
                self.data = pd.read_csv(path)
            elif data == 'excel':
                self.data = pd.read_excel(path)
            elif data == 'mysql':
                self.data = pd.read_sql(sql, conn)
            else:
                print('没有该文本文件')
        except (FileNotFoundError, AttributeError):
            print('输入的文件路径或者文件类型有误')

    def get_data_to_list(self):
        try:
            return self.data.values.tolist()
        except (FileNotFoundError, AttributeError):
            print('输入的文件路径或者文件类型有误')

    def get_data_to_dict(self):
        try:
            return [self.data.loc[i].to_dict() for i in self.data.index.values]
        except (FileNotFoundError, AttributeError):
            print('输入的文件路径或者文件类型有误')


if __name__ == '__main__':
    # data = DataOperation('mysql', sql='select * from student')
    # pprint(data.data.head())
    # pprint(data.get_data_to_list())
    # pprint(data.get_data_to_dict())
    # data = DataOperation('csv', path='..//data/lj_data.csv')
    # pprint(data.data.head())
    # pprint(data.get_data_to_list())
    # pprint(data.get_data_to_dict())
    data = DataOperation('excel', path='..//data/user_login.xls')
    pprint(data.data.head())
    pprint(data.get_data_to_list())
    pprint(data.get_data_to_dict())
